<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="450px" @open="open" @close="close">
    <el-form class="tl-form startTaskEditForm" ref="form" :model="model" :rules="rules" label-width="150px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="实际开始日期" prop="actualstartdate">
            <el-date-picker v-model="model.actualstartdate" :picker-options="pickerOptions" @change="selectTime(actualstartdate)" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" :disabled="isFinish"> </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="GpmProjectTaskFeedback" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit">确认 </el-button>
      <!-- <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit">
        <svg-icon icon-class="send" />提交更新
      </el-button> -->
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: {},
  data() {
    return {
      moduleTitle: '开始任务',
      urlPrefix: '/sd/projectTaskFeedback/',
      url: {
        // 额外的url
        queryCodeList: '/sd/projectTask/dataCodeList',
        start: '/sd/projectTask/start'
      },
      isFinish: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() >= Date.now()
        }
      }
    }
  },
  methods: {
    assignDefaultValue() {
      if (this.isAdd) {
        if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
          this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        }
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'applyusercode', this.user.code)
        this.$set(this.model, 'applyusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'feedbackdate', new Date())
        this.$set(this.model, 'taskid', this.taskid)
        this.$set(this.model, 'taskname', this.taskname)
        this.$set(this.model, 'taskschedule', this.taskschedule)
        this.$set(this.model, 'taskstate', this.taskstate)
        this.planstartdate = this.planstartdate.substring(0, 10)
        this.planenddate = this.planenddate.substring(0, 10)
        this.taskdistributedate = this.taskdistributedate.substring(0, 10)
        this.$set(this.model, 'planstartdate', this.planstartdate)
        this.$set(this.model, 'planenddate', this.planenddate)
        this.$set(this.model, 'taskdistributedate', this.taskdistributedate)
      }
    },
    loaded() {
      // 页面加载完毕执行
      // if (!this.isAdd && this.model.docno) {
      //   this.title = this.title + `（单据编号：${this.model.docno}）`
      // }
    },
    queryData(id) {
      if (!this.url.load) {
        this.$tap.alert('请设置load地址!', 'warning')
        return
      }
      return getAction('/sd/projectTask/load', { id: this.taskid }).then((res) => {
        if (res.success) {
          this.model = res.result
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** 保存确认 */
    doSubmitEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      if (this.model.actualstartdate === null || this.model.actualstartdate === undefined) {
        this.$tap.alert('请选择实际开始时间', 'warning')
        return
      }
      var param = {
        ids: this.taskid,
        actualstartdate: this.model.actualstartdate
      }
      postAction(this.url.start, param).then((res) => {
        if (res.success) {
          this.$tap.message(res.message, 'success')
          this.$emit('refresh')
          this.visible = false
          this.loadData()
        } else {
          this.$tap.alert(res.message, 'warning')
        }
        this.saveLoading = false
      })
      // this.$refs.form.validate(valid => {
      //   if (valid) {
      //     if (this.isAdd) {
      //       this.doAdd()
      //       return true
      //     } else {
      //       this.doEdit()
      //     }
      //   } else {
      //     return false
      //   }
      // })
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      postAction(this.url.add + '?billuid=' + this.uid, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.model = res.result
            this.visible = false
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    /** 提交审批 */
    doSubmitApproval() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.model.taskschedule === 100 && !this.model.taskactualenddate) {
            this.$tap.alert('请填写实际完成日期！')
            return
          }
          if (this.model.taskschedule !== 100) {
            this.$set(this.model, 'taskactualenddate', '')
          }
          if (this.model.taskactualenddate !== '') {
            var a = new Date(this.model.taskdistributedate)
            var b = new Date(this.model.taskactualenddate)
            if (a.getTime() > b.getTime()) {
              this.$tap.alert('实际完成日期不能小于任务派发日期！')
              return
            }
          }
          if (this.model.taskschedule === 100) {
            this.$set(this.model, 'taskstate', '2')
          }
          if (this.model.taskstate === '2') {
            this.$set(this.model, 'taskschedule', 100)
          }
          if (this.model.taskstate === '0') {
            this.$tap.alert('任务已开始，请选择正确的任务状态!', 'warning')
            return
          }
          if (!this.url.submit) {
            this.$tap.alert('请设置审批地址!', 'warning')
            return
          }
          if (!this.beforeApproval()) {
            return
          }
          this.submitLoading = true
          this.$tap
            .confirm('确定提交更新吗？提交后，更新内容不可修改！')
            .then((_) => {
              putAction(this.url.submit, this.model).then((res) => {
                if (res.success) {
                  this.$tap.message(res.message, 'success')
                  this.afterApproval()
                  this.visible = false
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
                this.submitLoading = false
              })
            })
            .catch((_) => {
              this.submitLoading = false
            })
        }
      })
    },
    setState() {
      if (this.model.taskstate === '2') {
        this.$set(this.model, 'taskschedule', 100)
      }
    },
    /** 页面打开时执行 - zhanglongfei 2019.10.18 */
    open() {
      this.model = {}
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        }
      })
    }
  },
  created() {
    this.doQueryCode()
  },
  /**  查询编码表*/
  doQueryCode() {
    if (this.url.queryCodeList) {
      getAction(this.url.queryCodeList, {}).then((res) => {
        if (res.success) {
          this.codeModel = res.result
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.startTaskEditForm {
  margin-top: 16px;
  margin-left: -50px;
}
</style>
